package org.openfans.web;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.openfans.domain.Facade;
import org.openfans.domain.Article;
import org.openfans.domain.Comment;
import org.openfans.util.ThreadFans;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

public class CommentArticleFormController extends SimpleFormController {
	private Facade facade = null;

	public void setFacade(Facade facade) {
		this.facade = facade;
	}

	public CommentArticleFormController() {
		setCommandName("comment");
		setCommandClass(Comment.class);
	}

	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		ThreadFans.authorize();
		String articleId = request.getParameter("id");

		Comment comment = (Comment) command;
		if ((articleId != null) && !articleId.equals("0")) {
			comment.setCommentDate(new Date());
			comment.setFans(ThreadFans.get());
			Article article = facade.getArticle(Integer.parseInt(articleId));
			facade.save(comment);
			article.addComment(comment);
			facade.save(article);
		}
		return new ModelAndView("redirect:viewArticle.html?id=" + articleId);
	}

	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {

		Comment comment = new Comment();

		return comment;
	}

}
